package com.rd.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.rd.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//TODO 解决登录后token刷新问题
//场景：用户登录后，访问首页(不需要登录也能访问),这样login拦截器不生效
//当token过期时间一到，用户又要重新登录
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // 因此这个拦截器，对于一切请求都放行，
    // 如果用户登录就保存用户信息到 UserHolder
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // TODO 基于token登录拦截
        // 请求头中获取token
        String token = request.getHeader("authorization");
        System.out.println("token:"+token);
        if (StrUtil.isBlank(token)){
            return true;
        }
        // 拼接key
        String key = RedisConstants.LOGIN_USER_KEY + token;
        // 从缓存中获取 userDTO(用户信息)
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        if (userMap.isEmpty()){
            return true;
        }

        // 将userMap 装配到userDTO
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        System.out.println("userDTO:"+userDTO);

        System.out.println("preHandle:线程id:"+Thread.currentThread().getId());
        // 保存用户信息
        UserHolder.saveUser(userDTO);

        //设置用户token过期时间
        stringRedisTemplate.expire(key,20, TimeUnit.MINUTES);
        // 移除过期时间，永不过期
//        stringRedisTemplate.persist(key);
        //6. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
